package com.example.hhh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hhh.model.pojo.Workorder;
import com.example.hhh.model.vo.WorkorderVO;
import com.example.hhh.service.WorkorderService;
import com.example.hhh.mapper.WorkorderMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/workorder")
@CrossOrigin(origins = "*")
public class WorkOrderController {
    @Autowired
    private WorkorderService workorderService;
    
    @Autowired
    private WorkorderMapper workorderMapper;

    /**
     * Excel批量导入工单数据
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importWorkorders(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择文件");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 校验Excel表头
            List<String> expectedHeaders = List.of("工单编号", "客户ID", "业务ID", "处理人员ID", "描述", "优先级", "状态", "接单时间", "完成时间", "完成用时(小时)");
            List<String> actualHeaders = readExcelHeaders(file);
            
            if (!actualHeaders.equals(expectedHeaders)) {
                result.put("success", false);
                result.put("message", "Excel模板不正确！请使用工单导入模板，表头必须包含：" + String.join(", ", expectedHeaders));
                return ResponseEntity.badRequest().body(result);
            }
            
            List<Workorder> workorders = readExcelFile(file);
            int successCount = 0;
            List<String> errors = new ArrayList<>();
            
            for (int i = 0; i < workorders.size(); i++) {
                try {
                    Workorder workorder = workorders.get(i);
                    
                    // 验证必填字段
                    if (workorder.getOrderNumber() == null || workorder.getOrderNumber().trim().isEmpty()) {
                        errors.add("第" + (i + 2) + "行：工单编号不能为空");
                        continue;
                    }
                    
                    if (workorder.getCustomerId() == null) {
                        errors.add("第" + (i + 2) + "行：客户ID不能为空");
                        continue;
                    }
                    
                    if (workorder.getBusinessId() == null) {
                        errors.add("第" + (i + 2) + "行：业务ID不能为空");
                        continue;
                    }
                    
                    if (workorder.getAssignedTo() == null) {
                        errors.add("第" + (i + 2) + "行：处理人员ID不能为空");
                        continue;
                    }
                    
                    // 检查工单编号是否重复
                    QueryWrapper<Workorder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("order_number", workorder.getOrderNumber().trim());
                    Workorder existingWorkorder = workorderService.getOne(queryWrapper);
                    if (existingWorkorder != null) {
                        errors.add("第" + (i + 2) + "行：工单编号'" + workorder.getOrderNumber().trim() + "'已存在，跳过导入");
                        continue;
                    }
                    
                    // 设置默认值
                    if (workorder.getOrderStatus() == null) {
                        workorder.setOrderStatus(0); // 新建状态
                    }
                    if (workorder.getPriority() == null) {
                        workorder.setPriority(2); // 默认中等优先级
                    }
                    workorder.setCreateTime(new Date());
                    workorder.setUpdateTime(new Date());
                    
                    // 检查插入结果
                    int insertResult = workorderMapper.insert(workorder);
                    if (insertResult > 0) {
                        successCount++;
                    } else {
                        errors.add("第" + (i + 2) + "行：数据库插入失败");
                    }
                } catch (Exception e) {
                    errors.add("第" + (i + 2) + "行导入失败：" + e.getMessage());
                    e.printStackTrace(); // 打印详细错误信息到控制台
                }
            }
            
            result.put("success", successCount > 0 || errors.isEmpty()); // 只有真正有成功插入或没有错误才算成功
            result.put("successCount", successCount);
            result.put("errorCount", errors.size());
            result.put("errors", errors);
            result.put("message", "导入完成，成功" + successCount + "条，失败" + errors.size() + "条");
            result.put("totalProcessed", workorders.size()); // 添加处理总数信息
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            result.put("stackTrace", sw.toString());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 读取Excel表头
     */
    private List<String> readExcelHeaders(MultipartFile file) throws IOException {
        List<String> headers = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            
            if (headerRow != null) {
                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    if (cell != null) {
                        headers.add(cell.toString().trim());
                    } else {
                        headers.add("");
                    }
                }
            }
        }
        
        return headers;
    }
    
    /**
     * 读取Excel文件
     */
    private List<Workorder> readExcelFile(MultipartFile file) throws IOException {
        List<Workorder> workorders = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                Workorder workorder = new Workorder();
                
                // 工单编号
                Cell orderNumberCell = row.getCell(0);
                if (orderNumberCell != null && !orderNumberCell.toString().trim().isEmpty()) {
                    workorder.setOrderNumber(orderNumberCell.toString().trim());
                } else {
                    continue; // 跳过空行
                }
                
                // 客户ID
                Cell customerIdCell = row.getCell(1);
                if (customerIdCell != null) {
                    try {
                        workorder.setCustomerId((int) customerIdCell.getNumericCellValue());
                    } catch (Exception e) {
                        workorder.setCustomerId(null);
                    }
                }
                
                // 业务ID
                Cell businessIdCell = row.getCell(2);
                if (businessIdCell != null) {
                    try {
                        workorder.setBusinessId((int) businessIdCell.getNumericCellValue());
                    } catch (Exception e) {
                        workorder.setBusinessId(null);
                    }
                }
                
                // 处理人员ID
                Cell assignedToCell = row.getCell(3);
                if (assignedToCell != null) {
                    try {
                        workorder.setAssignedTo((int) assignedToCell.getNumericCellValue());
                    } catch (Exception e) {
                        workorder.setAssignedTo(null);
                    }
                }
                
                // 描述
                Cell descCell = row.getCell(4);
                if (descCell != null) {
                    workorder.setDescription(descCell.toString().trim());
                }
                
                // 优先级
                Cell priorityCell = row.getCell(5);
                if (priorityCell != null) {
                    try {
                        workorder.setPriority((int) priorityCell.getNumericCellValue());
                    } catch (Exception e) {
                        workorder.setPriority(2); // 默认中等优先级
                    }
                }
                
                // 状态
                Cell statusCell = row.getCell(6);
                if (statusCell != null) {
                    try {
                        workorder.setOrderStatus((int) statusCell.getNumericCellValue());
                    } catch (Exception e) {
                        workorder.setOrderStatus(0); // 默认新建状态
                    }
                }
                
                // 设置时间字段
                workorder.setCreateTime(new Date());
                workorder.setUpdateTime(new Date());
                
                workorders.add(workorder);
            }
        }
        
        return workorders;
    }

    /**
     * 导出工单数据到Excel
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportWorkorders() {
        try {
            List<Workorder> workorders = workorderService.list();
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("工单信息");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] excelHeaders = {"工单编号", "客户ID", "业务ID", "处理人员ID", "描述", "优先级", "状态", "接单时间", "完成时间", "完成用时(小时)"};
            for (int i = 0; i < excelHeaders.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(excelHeaders[i]);
            }
            
            // 填充数据
            for (int i = 0; i < workorders.size(); i++) {
                Workorder workorder = workorders.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(workorder.getOrderNumber() != null ? workorder.getOrderNumber() : "");
                row.createCell(1).setCellValue(workorder.getCustomerId() != null ? workorder.getCustomerId() : 0);
                row.createCell(2).setCellValue(workorder.getBusinessId() != null ? workorder.getBusinessId() : 0);
                row.createCell(3).setCellValue(workorder.getAssignedTo() != null ? workorder.getAssignedTo() : 0);
                row.createCell(4).setCellValue(workorder.getDescription() != null ? workorder.getDescription() : "");
                row.createCell(5).setCellValue(workorder.getPriority() != null ? workorder.getPriority() : 2);
                row.createCell(6).setCellValue(workorder.getOrderStatus() != null ? workorder.getOrderStatus() : 0);
                row.createCell(7).setCellValue(workorder.getCreateTime() != null ? workorder.getCreateTime().toString() : "");
                row.createCell(8).setCellValue(workorder.getActualCompleteTime() != null ? workorder.getActualCompleteTime().toString() : "");
                
                // 计算完成用时
                if (workorder.getCreateTime() != null && workorder.getActualCompleteTime() != null) {
                    long diffMs = workorder.getActualCompleteTime().getTime() - workorder.getCreateTime().getTime();
                    double diffHours = Math.round((diffMs / (1000.0 * 60 * 60)) * 100) / 100.0;
                    row.createCell(9).setCellValue(diffHours);
                } else {
                    row.createCell(9).setCellValue("");
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < excelHeaders.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            byte[] bytes = outputStream.toByteArray();
            
            // 保存文件到指定目录
            String exportDir = "C:\\Users\\20642\\Desktop\\daochu";
            File dir = new File(exportDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            String fileName = "工单信息_" + System.currentTimeMillis() + ".xlsx";
            String filePath = exportDir + "\\" + fileName;
            File file = new File(filePath);
            
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                fileOut.write(bytes);
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 工单回单（完成工单）
     */
    @PutMapping("/{id}/complete")
    public ResponseEntity<Map<String, Object>> completeWorkorder(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Workorder workorder = workorderService.getById(id);
            if (workorder == null) {
                result.put("success", false);
                result.put("message", "工单不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查工单状态
            if (workorder.getOrderStatus() == 2) {
                result.put("success", false);
                result.put("message", "工单已完成，无需重复操作");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getOrderStatus() == 3) {
                result.put("success", false);
                result.put("message", "工单已退回，无法完成");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 更新工单状态为已完成
            workorder.setOrderStatus(2);
            workorder.setActualCompleteTime(new Date());
            workorder.setUpdateTime(new Date());
            
            boolean success = workorderService.updateById(workorder);
            
            result.put("success", success);
            result.put("message", success ? "工单完成成功" : "工单完成失败");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 工单退单
     */
    @PutMapping("/{id}/return")
    public ResponseEntity<Map<String, Object>> returnWorkorder(@PathVariable Integer id, 
                                                              @RequestParam(required = false) String reason) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Workorder workorder = workorderService.getById(id);
            if (workorder == null) {
                result.put("success", false);
                result.put("message", "工单不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查工单状态
            if (workorder.getOrderStatus() == 2) {
                result.put("success", false);
                result.put("message", "工单已完成，无法退回");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getOrderStatus() == 3) {
                result.put("success", false);
                result.put("message", "工单已退回，无需重复操作");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 更新工单状态为已退回
            workorder.setOrderStatus(3);
            workorder.setUpdateTime(new Date());
            
            // 如果有退回原因，可以添加到描述中
            if (reason != null && !reason.trim().isEmpty()) {
                String currentDesc = workorder.getDescription() != null ? workorder.getDescription() : "";
                workorder.setDescription(currentDesc + "\n退回原因：" + reason);
            }
            
            boolean success = workorderService.updateById(workorder);
            
            result.put("success", success);
            result.put("message", success ? "工单退回成功" : "工单退回失败");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 根据区域查询工单（这里用客户地址作为区域标识）
     */
    @GetMapping("/area/{area}")
    public ResponseEntity<List<Workorder>> getWorkordersByArea(@PathVariable String area) {
        try {
            // 这里需要关联查询客户表来获取区域信息
            // 由于工单表中有customerId，可以通过关联查询来实现
            // 简化实现：直接返回所有工单，前端可以根据客户信息过滤
            List<Workorder> workorders = workorderService.list();
            return ResponseEntity.ok(workorders);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据状态查询工单
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Workorder>> getWorkordersByStatus(@PathVariable Integer status) {
        try {
            QueryWrapper<Workorder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_status", status);
            List<Workorder> workorders = workorderService.list(queryWrapper);
            return ResponseEntity.ok(workorders);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    // 新增
    @PostMapping
    public ResponseEntity<Map<String, Object>> addWorkorder(@RequestBody Workorder workorder) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证必填字段
            if (workorder.getOrderNumber() == null || workorder.getOrderNumber().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "工单编号不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getCustomerId() == null) {
                result.put("success", false);
                result.put("message", "客户ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getBusinessId() == null) {
                result.put("success", false);
                result.put("message", "业务ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getAssignedTo() == null) {
                result.put("success", false);
                result.put("message", "处理人员不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 设置默认值
            if (workorder.getOrderStatus() == null) {
                workorder.setOrderStatus(0); // 新建状态
            }
            if (workorder.getPriority() == null) {
                workorder.setPriority(2); // 默认中等优先级
            }
            workorder.setCreateTime(new Date());
            workorder.setUpdateTime(new Date());
            
            boolean success = workorderService.save(workorder);
            
            result.put("success", success);
            result.put("message", success ? "工单创建成功" : "工单创建失败");
            if (success) {
                result.put("data", workorder);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建工单失败：" + e.getMessage());
            java.io.StringWriter sw = new java.io.StringWriter();
            e.printStackTrace(new java.io.PrintWriter(sw));
            result.put("stackTrace", sw.toString());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }

    // 删除
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteWorkorder(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = workorderService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败，数据不存在或有关联数据");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // 修改
    @PutMapping
    public ResponseEntity<Map<String, Object>> updateWorkorder(@RequestBody Workorder workorder) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证必填字段
            if (workorder.getOrderId() == null) {
                result.put("success", false);
                result.put("message", "工单ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getOrderNumber() == null || workorder.getOrderNumber().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "工单编号不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getCustomerId() == null) {
                result.put("success", false);
                result.put("message", "客户ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getBusinessId() == null) {
                result.put("success", false);
                result.put("message", "业务ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (workorder.getAssignedTo() == null) {
                result.put("success", false);
                result.put("message", "处理人员不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            workorder.setUpdateTime(new Date());
            boolean success = workorderService.updateById(workorder);
            
            result.put("success", success);
            result.put("message", success ? "工单更新成功" : "工单更新失败");
            if (success) {
                result.put("data", workorder);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新工单失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }

    // 查询单个
    @GetMapping("/{id}")
    public WorkorderVO getWorkorder(@PathVariable Integer id) {
        return workorderService.getWorkorderWithDetails(id);
    }

    // 查询所有
    @GetMapping("/list")
    public Map<String, Object> getAllWorkorder(@RequestParam(defaultValue = "1") Integer page,
                                               @RequestParam(defaultValue = "12") Integer limit,
                                               @RequestParam(required = false) String search,
                                               @RequestParam(required = false) Integer status,
                                               @RequestParam(required = false) Integer priority) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<WorkorderVO> pageParam = new Page<>(page, limit);
            IPage<WorkorderVO> pageResult = workorderService.getWorkorderPageWithDetails(pageParam, search, status, priority);
            // 调试打印VO对象内容
            System.out.println("工单VO数据: " + pageResult.getRecords());
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
        } catch (Exception e) {
            result.put("records", new ArrayList<>());
            result.put("total", 0);
            result.put("pages", 0);
            result.put("current", page);
            result.put("size", limit);
            e.printStackTrace();
        }
        return result;
    }

    // 分页查询
    @GetMapping("/page")
    public IPage<Workorder> getWorkorderPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Workorder> page = new Page<>(pageNum, pageSize);
        return workorderService.page(page, new QueryWrapper<>());
    }
}
